package com.xln.furns.Filter;

import com.google.gson.Gson;
import com.xln.furns.entity.Manage;
import com.xln.furns.entity.Member;
import com.xln.furns.service.ManageService;
import com.xln.furns.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */

public class AuthFilter implements Filter {
    private List<String> excludeUrls;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        String strExcludeUrls = filterConfig.getInitParameter("excludeUrls");
        String[] splitUrl = strExcludeUrls.split(",");
        excludeUrls = Arrays.asList(splitUrl);
//        System.out.printf("excludeUrls= "+excludeUrls);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String url = request.getServletPath();

        Member member =(Member) request.getSession().getAttribute("member");
        Manage manage = (Manage) request.getSession().getAttribute("manage");

        if (!excludeUrls.contains(url)) {
            if (member == null && manage == null) {

                if (!WebUtils.isAjaxRequest(request)) {
                    request.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
                    return;
                } else {
                    Map<String, Object> urlMap = new HashMap<>();
                    urlMap.put("url","views/member/login.jsp");
                    String urlJson = new Gson().toJson(urlMap);
                    servletResponse.getWriter().write(urlJson);
                }
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
